<script setup>
import {
  getGoodsPrice,
  deleteGoodsPrice,
  saveGoodsPrice,
  getGoodsPriceById,
} from '@/api/goodsPrice'
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import logger from '@/utils/logger'
import { formatDateTime } from '@/utils/dayjs'
import AddGoodsPrice from './components/AddGoodsPrice.vue'

const dialogVisible = ref(false)
const currentPrice = ref(null)
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)

const detailVisible = ref(false)
const approvalDialogVisible = ref(false)

// 查询条件
const queryFields = ref({ priceNo: '' })

const openAddDialog = () => {
  currentPrice.value = null
  dialogVisible.value = true
}

const openEditDialog = async (row) => {
  try {
    loading.value = true
    // 编辑前也需要获取完整数据
    const res = await getGoodsPriceById(row.updatePriceMId)
    if (res.success && res.data) {
      currentPrice.value = res.data
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取调价单数据失败')
    }
  } catch (error) {
    logger.error('获取调价单数据失败', error)
    ElMessage.error('获取调价单数据失败')
  } finally {
    loading.value = false
  }
}

const openDetailDialog = async (row) => {
  try {
    loading.value = true
    // 使用专门的详情接口获取完整数据
    const res = await getGoodsPriceById(row.updatePriceMId)
    if (res.success && res.data) {
      currentPrice.value = res.data
      detailVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取调价单详情失败')
    }
  } catch (error) {
    logger.error('获取调价单详情失败', error)
    ElMessage.error('获取调价单详情失败')
  } finally {
    loading.value = false
  }
}

const openApprovalDialog = async (row) => {
  try {
    loading.value = true
    // 审核前也需要获取完整数据
    const res = await getGoodsPriceById(row.updatePriceMId)
    if (res.success && res.data) {
      currentPrice.value = res.data
      approvalDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取调价单数据失败')
    }
  } catch (error) {
    logger.error('获取调价单数据失败', error)
    ElMessage.error('获取调价单数据失败')
  } finally {
    loading.value = false
  }
}

const closeDialog = () => {
  dialogVisible.value = false
  detailVisible.value = false
  approvalDialogVisible.value = false
}

const fetchPriceData = async () => {
  loading.value = true
  try {
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      queryFields: { priceNo: queryFields.value.priceNo.trim() || null },
    }
    const res = await getGoodsPrice(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取列表失败')
    }
  } catch (error) {
    logger.error('获取调价单列表失败', error)
  } finally {
    loading.value = false
  }
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确定删除调价单?`, '提示', { type: 'warning' })
  try {
    await deleteGoodsPrice(row.updatePriceMId)
    ElMessage.success('删除成功')
    fetchPriceData()
  } catch (error) {
    logger.error('删除调价单失败', error)
  }
}

const handleApprovalConfirm = async () => {
  try {
    const payload = { ...currentPrice.value, editType: 2, isCheck: true }
    await saveGoodsPrice(payload)
    ElMessage.success('审核成功')
    closeDialog()
    fetchPriceData()
  } catch (error) {
    logger.error('审核失败', error)
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPriceData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPriceData()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchPriceData()
}

const resetSearch = () => {
  queryFields.value.priceNo = ''
  fetchPriceData()
}

const handleSuccess = () => {
  fetchPriceData()
  closeDialog()
}

onMounted(fetchPriceData)
</script>

<template>
  <!-- Dialogs for add/edit, details, and approval -->
  <el-dialog
    v-model="dialogVisible"
    :title="currentPrice ? '编辑调价单' : '新增调价单'"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoodsPrice v-model="currentPrice" @success="handleSuccess" @close="closeDialog" />
  </el-dialog>

  <el-dialog
    v-model="detailVisible"
    title="调价单详情"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoodsPrice v-model="currentPrice" is-preview @close="closeDialog" />
  </el-dialog>

  <el-dialog
    v-model="approvalDialogVisible"
    title="审核调价单"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoodsPrice v-model="currentPrice" is-preview hide-footer />
    <template #footer>
      <el-button type="primary" @click="handleApprovalConfirm">
        <template #icon>
          <el-icon><LineMdCheckAll /></el-icon>
        </template>
        审核通过
      </el-button>
      <el-button @click="closeDialog">
        <template #icon>
          <el-icon><LineMdClose /></el-icon>
        </template>
        取消
      </el-button>
    </template>
  </el-dialog>

  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="queryFields" @submit.prevent="handleSearch">
          <el-form-item label="调价单号">
            <el-input v-model="queryFields.priceNo" placeholder="请输入单号" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="controller-item">
        <el-form-item>
          <el-button type="primary" @click="openAddDialog">
            <template #icon>
              <el-icon><LineMdPlus /></el-icon>
            </template>
            新增调价单
          </el-button>
        </el-form-item>
      </div>
    </div>

    <div class="table-container">
      <el-table :data="tableData" v-loading="loading" row-key="updatePriceMId">
        <el-table-column width="200" prop="priceNo" label="调价单号">
          <template #default="{ row }">
            {{ row.priceNo || '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="operatorName" label="操作员">
          <template #default="{ row }">
            {{ row.operatorName || '暂无' }}
          </template>
        </el-table-column>
        <el-table-column width="180" prop="priceTime" label="创建时间">
          <template #default="{ row }">
            {{ row.priceTime ? formatDateTime(row.priceTime) : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="isCheck" label="审核状态">
          <template #default="{ row }">
            <el-tag :type="row.isCheck ? 'success' : 'warning'">
              {{ row.isCheck ? '已审核' : '未审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkerName" label="审核人">
          <template #default="{ row }">
            <el-tag v-if="!row.checkerName" type="info" size="small">暂无</el-tag>
            <template v-else>{{ row.checkerName }}</template>
          </template>
        </el-table-column>
        <el-table-column width="180" prop="checkTime" label="审核时间">
          <template #default="{ row }">
            <el-tag v-if="!row.checkTime" type="info" size="small">暂无</el-tag>
            <template v-else>{{ formatDateTime(row.checkTime) }}</template>
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注">
          <template #default="{ row }">
            <el-tag v-if="!row.notes" type="info" size="small">暂无</el-tag>
            <template v-else>{{ row.notes }}</template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="!row.isCheck"
              type="success"
              size="small"
              @click="openApprovalDialog(row)"
              ><template #icon>
                <el-icon><LineMdCheckAll /></el-icon>
              </template>
              审核</el-button
            >
            <el-button
              type="primary"
              size="small"
              :disabled="row.isCheck"
              @click="openEditDialog(row)"
              ><template #icon>
                <el-icon><LineMdEdit /></el-icon>
              </template>
              编辑</el-button
            >
            <el-button type="info" size="small" @click="openDetailDialog(row)">
              <template #icon>
                <el-icon><LineMdWatchLoop /></el-icon>
              </template>
              详情
            </el-button>
            <el-button type="danger" size="small" :disabled="row.isCheck" @click="handleDelete(row)"
              ><template #icon>
                <el-icon><LineMdTrash /></el-icon>
              </template>
              删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[15, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;
    .el-table {
      flex: 1;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
